<?php
require_once ($_SERVER["DOCUMENT_ROOT"] ."/include/config.php");
require_once ("sql.php");

class UserController extends BaseController {
	static public function ProcessRequest($request) {
		self::SQL_connect();

		if ($request == "get_user" && isset($_POST["id"]))
			self::GetUser($_POST["id"]);
		else if ($request == "save" && isset($_POST["data"]))
			self::SaveUser(json_decode($_POST["data"]));
		else if ($request == "delete" && isset($_POST["id"]))
			self::DeleteUser($_POST["id"]);
		else if ($request == 'settings' && isset($_POST["data"])) 
			self::UpdateUserSettings(json_decode($_POST["data"]));
		
		self::SQL_close();
	}

	static private function GetUser($id) {
		$query = "SELECT * from users WHERE user_id = '$id'";
		if ($result = self::$db_link -> query($query))
			echo json_encode($result -> fetch_object());
	}
	
	static private function UpdateUserSettings($data) {
		$query = "UPDATE users SET location = '$data->location', zoom = $data->zoom, layer = $data->layer WHERE user_id = '$data->id' ";
		self::ProcessQuery($query);
	}

	static private function SaveUser($data) {
		$pass = md5(md5($data -> pass));
		if ($data -> pass != "")
			$query = "INSERT INTO users (user_id, user_login, user_password, admin) VALUES ('$data->id','$data->login','$pass',$data->admin)
			ON DUPLICATE KEY UPDATE user_login = '$data->login', user_password ='$pass', admin = $data->admin;";
		else
			$query = "INSERT INTO users (user_id, user_login, admin) VALUES ('$data->id','$data->login',$data->admin)
			ON DUPLICATE KEY UPDATE user_login = '$data->login', admin = $data->admin;";

		self::ProcessQuery($query);
	}

	static private function DeleteUser($id) {
		$query = "DELETE FROM users WHERE user_id='$id';";
		self::ProcessQuery($query);
	}
}

UserController::$config = $config;
if (isset($_POST["op"]))
	UserController::ProcessRequest($_POST["op"]);
?>